package com.paratice.zookeeper;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ConnectionDemo {
	
	public static void main(String[] args) {
		try {
			CountDownLatch countDownLatch = new CountDownLatch(1);
			ZooKeeper zookeeper = new ZooKeeper("192.168.2.200:2181", 4000, new Watcher() {
				
				@Override
				public void process(WatchedEvent event) {
					if (Event.KeeperState.SyncConnected == event.getState()) {
						countDownLatch.countDown();
					}
				}
			});
			countDownLatch.await();
			System.out.println(zookeeper.getState());
			
			//创建节点
			zookeeper.create("/zk-persis", "1".getBytes(), 
					Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			
			Thread.sleep(1000);
			
			//更新节点
			Stat stat = new Stat();
			byte[] data  = zookeeper.getData("/zk-persis", null, stat);
			System.out.println(new String(data));
			zookeeper.setData("/zk-persis", "aa".getBytes(), stat.getVersion());
			
			//删除节点
			byte[] data1  = zookeeper.getData("/zk-persis", null, stat);
			System.out.println(new String(data1));
			zookeeper.delete("/zk-persis", stat.getVersion());
			
			zookeeper.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
